package com.ycy.login;

import java.util.HashSet;
import java.util.Set;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.ycy.pojo.Employee;
import com.ycy.pojo.Role;
import com.ycy.service.Role.RoleService;
import com.ycy.service.employee.EmployService;

/*
 * shiro的认证登录
 * 
 * */
public class MyRealm extends AuthorizingRealm {

	@Autowired
	private EmployService employservice;
	@Autowired 
	private RoleService roleService;
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		// TODO Auto-generated method stub
		Set<String> roles=new HashSet<String>();
		String name =(String) principals.getPrimaryPrincipal();
		Role role =roleService.findByName(name);
		roles.add(role.getRole());
		return new SimpleAuthorizationInfo(roles);

	} 
   //认证
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		// TODO Auto-generated method stub
		//加这一步的目的是在Post请求的时候会先进认证，然后在到请求
		UsernamePasswordToken t=(UsernamePasswordToken)token ;
		Employee employee=employservice.login(t.getUsername(),new String(t.getPassword()));
		if(employee==null){
			throw new AuthenticationException();
		}
	return new SimpleAuthenticationInfo(token.getPrincipal(), token.getCredentials(), getName());
	}
}
